// 应用状态管理

import React, { createContext, useContext, useReducer, useEffect, ReactNode } from 'react';
import { AppState, Scene, UserProgress, Word } from '../types';
import { storageManager } from '../utils/storage';
import { aiService } from '../services/aiService';
import { toast } from 'react-hot-toast';

// 初始状态
const initialState: AppState = {
  selectedWords: [],
  isGeneratingScene: false,
  learningMode: 'input',
  userProgress: storageManager.getUserProgress(),
  savedScenes: storageManager.getSavedScenes(),
  voiceEnabled: true,
  language: 'en'
};

// Action 类型
type AppAction = 
  | { type: 'SET_SELECTED_WORDS'; payload: string[] }
  | { type: 'SET_LEARNING_MODE'; payload: 'input' | 'scene' | 'learning' }
  | { type: 'SET_CURRENT_SCENE'; payload: Scene | undefined }
  | { type: 'SET_GENERATING_SCENE'; payload: boolean }
  | { type: 'UPDATE_USER_PROGRESS'; payload: Partial<UserProgress> }
  | { type: 'ADD_SAVED_SCENE'; payload: Scene }
  | { type: 'REMOVE_SAVED_SCENE'; payload: string }
  | { type: 'TOGGLE_VOICE'; }
  | { type: 'SET_LANGUAGE'; payload: 'en' | 'zh' }
  | { type: 'RESET_STATE' };

// Reducer
function appReducer(state: AppState, action: AppAction): AppState {
  switch (action.type) {
    case 'SET_SELECTED_WORDS':
      return { ...state, selectedWords: action.payload };
    
    case 'SET_LEARNING_MODE':
      return { ...state, learningMode: action.payload };
    
    case 'SET_CURRENT_SCENE':
      return { ...state, currentScene: action.payload };
    
    case 'SET_GENERATING_SCENE':
      return { ...state, isGeneratingScene: action.payload };
    
    case 'UPDATE_USER_PROGRESS':
      const updatedProgress = { ...state.userProgress, ...action.payload };
      storageManager.saveUserProgress(updatedProgress);
      return { ...state, userProgress: updatedProgress };
    
    case 'ADD_SAVED_SCENE':
      const newScenes = [...state.savedScenes, action.payload];
      storageManager.saveScene(action.payload);
      return { ...state, savedScenes: newScenes };
    
    case 'REMOVE_SAVED_SCENE':
      const filteredScenes = state.savedScenes.filter(s => s.id !== action.payload);
      storageManager.deleteScene(action.payload);
      return { ...state, savedScenes: filteredScenes };
    
    case 'TOGGLE_VOICE':
      return { ...state, voiceEnabled: !state.voiceEnabled };
    
    case 'SET_LANGUAGE':
      return { ...state, language: action.payload };
    
    case 'RESET_STATE':
      storageManager.clearAllData();
      return initialState;
    
    default:
      return state;
  }
}

// Context 类型
interface AppContextType {
  state: AppState;
  dispatch: React.Dispatch<AppAction>;
  // 便捷方法
  setSelectedWords: (words: string[]) => void;
  setLearningMode: (mode: 'input' | 'scene' | 'learning') => void;
  setCurrentScene: (scene: Scene | undefined) => void;
  addWordToLearned: (word: Word) => void;
  updateProgress: (progress: Partial<UserProgress>) => void;
  generateScene: (words: string[]) => Promise<void>;
}

// 创建 Context
const AppContext = createContext<AppContextType | undefined>(undefined);

// Provider 组件
export function AppProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(appReducer, initialState);

  // 便捷方法
  const setSelectedWords = (words: string[]) => {
    dispatch({ type: 'SET_SELECTED_WORDS', payload: words });
  };

  const setLearningMode = (mode: 'input' | 'scene' | 'learning') => {
    dispatch({ type: 'SET_LEARNING_MODE', payload: mode });
  };

  const setCurrentScene = (scene: Scene | undefined) => {
    dispatch({ type: 'SET_CURRENT_SCENE', payload: scene });
  };

  const addWordToLearned = (word: Word) => {
    storageManager.saveLearnedWord(word);
    // 更新进度
    dispatch({ 
      type: 'UPDATE_USER_PROGRESS', 
      payload: { 
        totalWordsLearned: state.userProgress.totalWordsLearned + 1,
        experience: state.userProgress.experience + 10
      }
    });
    toast.success(`学会了单词: ${word.text}! 🎉`);
  };

  const updateProgress = (progress: Partial<UserProgress>) => {
    dispatch({ type: 'UPDATE_USER_PROGRESS', payload: progress });
  };

  // 生成场景（使用真实的 AI 服务）
  const generateScene = async (words: string[]) => {
    dispatch({ type: 'SET_GENERATING_SCENE', payload: true });
    
    try {
      // 首先检查 AI 服务是否可用
      const isHealthy = await aiService.healthCheck();
      if (!isHealthy) {
        toast.error('AI 服务暂时不可用，将使用模拟场景');
        return generateMockScene(words);
      }

      // 调用 AI 服务生成场景
      const aiResponse = await aiService.generateScene({
        words,
        language: state.language,
        difficulty: 'intermediate',
        sceneType: 'daily'
      });
      
      // 创建场景对象
      const scene: Scene = {
        id: Date.now().toString(),
        words: words,
        imageUrl: `/api/placeholder/800/600`, // 暂时使用占位图，后续可以集成图像生成服务
        title: aiResponse.title,
        description: aiResponse.description,
        createdAt: new Date(),
        favorited: false,
        hotspots: aiResponse.wordContexts.map((wc, index) => ({
          id: `hotspot-${index}`,
          wordId: wc.word,
          x: wc.position.x,
          y: wc.position.y,
          width: 120,
          height: 50
        })),
        imagePrompt: aiResponse.imagePrompt, // 保存图像生成提示
        aiGenerated: true // 标记为 AI 生成
      };
      
      dispatch({ type: 'SET_CURRENT_SCENE', payload: scene });
      dispatch({ type: 'ADD_SAVED_SCENE', payload: scene });
      dispatch({ type: 'SET_LEARNING_MODE', payload: 'learning' });
      
      // 更新进度
      dispatch({ 
        type: 'UPDATE_USER_PROGRESS', 
        payload: { 
          totalScenesCreated: state.userProgress.totalScenesCreated + 1,
          experience: state.userProgress.experience + 100 // AI 生成给更多经验
        }
      });
      
      toast.success('AI 场景生成成功！🎉');
    } catch (error) {
      console.error('AI scene generation error:', error);
      toast.error('AI 场景生成失败，使用备用方案');
      // 降级到模拟场景
      await generateMockScene(words);
    } finally {
      dispatch({ type: 'SET_GENERATING_SCENE', payload: false });
    }
  };

  // 备用的模拟场景生成
  const generateMockScene = async (words: string[]) => {
    // 模拟延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const scene: Scene = {
      id: Date.now().toString(),
      words: words,
      imageUrl: `/api/placeholder/800/600`,
      title: `学习场景：${words.join('、')}`,
      description: `这是一个包含单词 ${words.join('、')} 的模拟学习场景。在真实的 AI 服务可用时，您将看到更生动的场景描述。`,
      createdAt: new Date(),
      favorited: false,
      hotspots: words.map((word, index) => ({
        id: `hotspot-${index}`,
        wordId: word,
        x: 20 + (index * 15), 
        y: 30 + (index * 10),
        width: 100,
        height: 40
      })),
      aiGenerated: false
    };
    
    dispatch({ type: 'SET_CURRENT_SCENE', payload: scene });
    dispatch({ type: 'ADD_SAVED_SCENE', payload: scene });
    dispatch({ type: 'SET_LEARNING_MODE', payload: 'learning' });
    
    dispatch({ 
      type: 'UPDATE_USER_PROGRESS', 
      payload: { 
        totalScenesCreated: state.userProgress.totalScenesCreated + 1,
        experience: state.userProgress.experience + 50
      }
    });
    
    toast.success('场景生成完成！');
  };

  const contextValue: AppContextType = {
    state,
    dispatch,
    setSelectedWords,
    setLearningMode,
    setCurrentScene,
    addWordToLearned,
    updateProgress,
    generateScene
  };

  return (
    <AppContext.Provider value={contextValue}>
      {children}
    </AppContext.Provider>
  );
}

// Hook
export function useApp() {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error('useApp must be used within an AppProvider');
  }
  return context;
}